//
//  QMainVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/1.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QMainVC.h"
#import "QMainFootView.h"
#import "QMySelfVC.h"
#import "QWebViewVC.h"
#import "QLoginVC.h"
#import "QPerfectOrderInforMationVC.h"
#import "QTopupMoneyVC.h"
#import "QFreeCertificateVC.h"
#import "QTawardVC.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "QPayPlayBoxView.h"
#import "QNoPayOrderModel.h"
#import "QForgetPayPassWordVC.h"
#import "QPaySuccessVC.h"
#import "QActiveWebViewVC.h"
#import "QPointShopVC.h"
#import "MJExtension.h"
#import "QMainMsgModel.h"
#import "QMessageVC.h"
#import "UITabBar+badge.h"
#import "QPointsVC.h"
#import "QActivityWebVC.h"
#import "ImgButtonLabel.h"
#import "CustomView.h"
#import "QCustomView.h"
#import "FileManager.h"
#import "DaiBanWebVC.h"
#import "QMainModel.h"
#import "MJExtension.h"
@interface QMainVC ()<AMapLocationManagerDelegate,AMapSearchDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, strong) AMapSearchAPI *search;

@property(nonatomic,strong)QMainHeadView *headview;

@property(nonatomic,strong)UILabel *sublabel;
@property (nonatomic,strong)NSMutableArray *bottomArray;
@property (nonatomic,strong)UIScrollView *footView;
@property (nonatomic,strong)UIView *midView;
@property (nonatomic,strong)UIButton *leftScroBtn;
@property (nonatomic,strong)UIButton *rightScroBtn;

@end

@implementation QMainVC{
    
    NSMutableArray *_imageArr;//所有的轮播图片地址
    NSMutableArray *_imgvoArr;//轮播的所有数据
    NSMutableArray *_activityTitleArr;//活动文字
    NSMutableArray *_activityImgArr;//活动的url
    NSInteger actIndex;
    NSTimer *_timer;
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    _imageArr = [NSMutableArray array];
    _imgvoArr = [NSMutableArray array];
    _bottomArray = [NSMutableArray array];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createUI];//创建ui
    [self requestData];//主页接口
    actIndex = 0;
    [self setLocationManager];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiAction:) name:kNotificationRegisterSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifiAction:) name:kNotificationTopUpMoneySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToAdVC) name:kNotificationPushToAdVC object:nil];//启动页广告走向
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestNoPayOrderData) name:kNotificationNoPayOrders object:nil];//未支付订单
    //     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAllData) name:kNotificationTabBar1 object:nil];
    //邀请好友
    [self testRequestData];
    [self requestActivityData];
    //    NSString *weekday = [self calculateWeek:[NSDate date]];
    
    //    if ([weekday isEqualToString:@"周五"]) {
    [self checkArchive];
    //    }
}

- (void)requestAllData{
    [self requestData];
    [self testRequestData];
}
- (void)pushToAdVC{
    
    NSString *url = [[NSUserDefaults standardUserDefaults] valueForKey:@"adUrl"];
    if (url.length>0) {
        QActiveWebViewVC  *vc = [[QActiveWebViewVC alloc] init];
        vc.url =url;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


- (void)notifiAction:(NSNotification *)notification{
    [self requestDataMySelf];
}

- (void)createUI{//注automaticallyAdjustsScrollViewInsets关系，第一个视图的contentsize往上偏64
    UIView *_bacView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight)];
    _bacView.backgroundColor = [QColorUtility defaultBackGroundColor];
    [self.view addSubview:_bacView];
    
    NSInteger height;
    if (kDevice_Is_iPhoneX) {
        height = 360;
    }else if(iphone6Plus_5_5){
        height = 360;
    }else if(iphone6_4_7){
        height = 300;
    }else if(iphone5x_4_0){
        height = 240;
    }else if (iphone4x_3_5){
        height = 190;
    }else{
        height = 190;
    }
    if (kDevice_Is_iPhoneX) {
         _headview = [[QMainHeadView alloc] initWithFrame:CGRectMake(0,40,kScreenWidth,height)];
    }else{
         _headview = [[QMainHeadView alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,height)];
    }
   
    _headview.delegate = self;
    [_bacView addSubview:_headview];
    
    UIView *newView = [[UIView alloc] initWithFrame:CGRectMake(0, _headview.bottom, kScreenWidth, 40)];
    newView.backgroundColor = [UIColor whiteColor];
    newView.layer.borderColor = [QColorUtility defaultLineColor].CGColor;
    newView.layer.borderWidth = 0.5;
    [_bacView addSubview:newView];
    
    UIButton *_newTitlebutton = [[UIButton alloc] initWithFrame:CGRectMake(10, 0,80, 40)];
    [_newTitlebutton setTitleColor:[QColorUtility defaultBlueColor] forState:UIControlStateNormal];
    [_newTitlebutton addTarget:self action:@selector(newButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_newTitlebutton setTitle:@"最新优惠" forState:UIControlStateNormal];
    [newView addSubview:_newTitlebutton];
    
    
    _sublabel = [QViewUtility createLabelWithFrame:CGRectMake(_newTitlebutton.right+10, 0, kScreenWidth-100, 40) font:Ksize15 textAlignment:NSTextAlignmentLeft textColor:[QColorUtility defaultDeepGrayColor] text:@""];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(newButtonAction)];
    newView.userInteractionEnabled = YES;
    _sublabel.userInteractionEnabled = YES;
    [_sublabel addGestureRecognizer:tap];
    [newView addSubview:_sublabel];
    
    NSInteger midViewH;
    if(iphone6Plus_5_5){
        midViewH = 190;
    }else if(iphone6_4_7){
        midViewH = 190;
    }else if(iphone5x_4_0){
        midViewH = 160;
    }else if (iphone4x_3_5){
        midViewH = 130;
    }else{
        midViewH = 190;
    }
    _midView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(newView.frame), kScreenWidth,midViewH)];
    QCustomView *leftView = [[QCustomView alloc]initWithFrame:CGRectMake(0, 0, _midView.bounds.size.width/2, _midView.bounds.size.height)];
    _midView.backgroundColor = [UIColor whiteColor];
    leftView.cImgView.image = [UIImage imageNamed:@"加油"];
//    leftView.cLabel.text = @"加油";
//    leftView.cLabel.font = [UIFont systemFontOfSize:18];
//    leftView.cLabel.textAlignment = NSTextAlignmentCenter;
    [leftView.cButton addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    leftView.tag = 10;
    [_midView addSubview:leftView];
    
    QCustomView *rightView = [[QCustomView alloc]initWithFrame:CGRectMake(_midView.bounds.size.width/2, 0, _midView.bounds.size.width/2, _midView.bounds.size.height)];
    rightView.cImgView.image = [UIImage imageNamed:@"充值"];
//    rightView.cLabel.text = @"充值";
//    rightView.cLabel.font = [UIFont systemFontOfSize:18];
//    rightView.cLabel.textAlignment = NSTextAlignmentCenter;
    [rightView.cButton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    rightView.tag = 11;
    [_midView addSubview:rightView];
    //左边下划线
    UIView *leftLineView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(leftView.frame), CGRectGetWidth(leftView.frame), 1)];
    leftLineView.backgroundColor = [UIColor lightGrayColor];
    leftLineView.alpha = 0.1;
    [_midView addSubview:leftLineView];
    //右边下划线
    UIView *rightLineView = [[UIView alloc]initWithFrame:CGRectMake(rightView.frame.size.width, CGRectGetMaxY(rightView.frame), CGRectGetWidth(rightView.frame), 1)];
    rightLineView.backgroundColor = [UIColor lightGrayColor];
    rightLineView.alpha = 0.1;
    [_midView addSubview:rightLineView];
    //中间下划线
    UIView *midlineView = [[UIView alloc]initWithFrame:CGRectMake(_midView.bounds.size.width/2-0.5, 0, 1, midViewH)];
    midlineView.backgroundColor = [UIColor lightGrayColor];
    [_midView addSubview:midlineView];
    midlineView.alpha = 0.1;
    [self.view addSubview:_midView];
    
    
    if (self.footView ==nil) {
        self.footView = [[UIScrollView alloc]init];
        self.footView.backgroundColor = [UIColor whiteColor];
    }
    [_bacView addSubview:self.footView];
    [self.footView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(_midView.mas_bottom).offset(0);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_bottom).offset(-44);
    }];
    
    //添加两侧点击滑动scrollView
    _leftScroBtn = [UIButton buttonWithType:0];
    [_leftScroBtn setBackgroundImage:[UIImage imageNamed:@"left_arrow"] forState:UIControlStateNormal];
    [_leftScroBtn addTarget:self action:@selector(scrollBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _leftScroBtn.tag = 50;
    [_bacView addSubview:_leftScroBtn];
    [_leftScroBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_footView);
        make.size.mas_equalTo(CGSizeMake(25, 25));
        make.right.equalTo(self.view).offset(-kScreenWidth+30);
        
    }];
    
    _rightScroBtn = [UIButton buttonWithType:0];
    [_rightScroBtn setBackgroundImage:[UIImage imageNamed:@"right_arrow"] forState:UIControlStateNormal];
    [_rightScroBtn addTarget:self action:@selector(scrollBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _rightScroBtn.tag = 51;
    [_bacView addSubview:_rightScroBtn];
    [_rightScroBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_footView);
        make.size.mas_equalTo(CGSizeMake(25, 25));
        make.right.equalTo(self.view).offset(0);
    }];
    _leftScroBtn.hidden = YES;
    _rightScroBtn.hidden = YES;
    
    
    UIButton *phonebtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 25+kStatusHeight, 32, 32)];
    [phonebtn setImage:[UIImage imageNamed:@"home_phone"] forState:0];
    [phonebtn addTarget:self action:@selector(navAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:phonebtn];
    
    
}
- (void)scrollBtnAction:(UIButton *)button{
    
    if (button.tag == 51) {
        
        CGFloat offsetX = self.footView.contentSize.width - self.footView.frame.size.width;
        [self.footView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
        
    }
    if (button.tag == 50) {
        
        [self.footView setContentOffset:CGPointMake(0, 0) animated:YES];
        
    }
    
}

- (void)pushToNextVC{
    if([QUserInfo sharedInfo].loginModel){
        if ([QUserInfo sharedInfo].unPayOrder == YES) {
            NSString *title = [NSString stringWithFormat:@"您有%@个订单尚未支付",[QUserInfo sharedInfo].unPayCount];
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:title leftTitle:@"继续下单" rightTitle:@"去支付" type:1 myBlock:^(NSInteger tag) {
                if(tag == 1){
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"kNotificationGoToPay" object:nil];
                    self.tabBarController.selectedIndex = 1;
                    
                }else if (tag == 0){
                    QPerfectOrderInforMationVC *vc = [[QPerfectOrderInforMationVC alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                    vc.nopaycount = [QUserInfo sharedInfo].unPayCount;
                }
            }];
            
        }else{
            QPerfectOrderInforMationVC *vc = [[QPerfectOrderInforMationVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        
    }else{
        [self notLogin];
    }
}
#pragma mark ---加油按钮点击方法
- (void)leftButtonAction:(UIButton *)button{
    UIView *leftView = [self.view viewWithTag:10];
    
    [UIView transitionWithView:leftView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        
    } completion:^(BOOL finished) {
        
        [self pushToNextVC];
        
    }];
}

#pragma mark ---充值按钮点击方法
- (void)rightButtonAction:(UIButton *)button{
    UIView *rightView = [self.view viewWithTag:11];
    [UIView transitionWithView:rightView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{
        
    } completion:^(BOOL finished) {
        if([QUserInfo sharedInfo].loginModel){
            QTopupMoneyVC *vc = [[QTopupMoneyVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [self notLogin];
        }
    }];
    
}


#pragma mark ---打电话点击方法
- (void)navAction:(UIButton *)btn{
    
    [QViewUtility showPlayBoxView:PlayboxCallPhoneStyle myBlock:^(NSInteger index) {
        if(index == 1){
            [QViewUtility callPhone];
        }
    }];
}


////点击最新优惠
- (void)newButtonAction{
    QWebViewVC *vc = [[QWebViewVC alloc] init];
    vc.style = WebNetWorkStyle;
    vc.title = @"最新优惠";
    if(_activityImgArr.count){
        vc.url = _activityImgArr[actIndex];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)runTimeTitle{
    
    if(_activityTitleArr.count){
        actIndex++;
        if(actIndex == _activityTitleArr.count){
            actIndex = 0;
        }
        [_sublabel.layer removeAllAnimations];
        CABasicAnimation *basic = [CABasicAnimation animationWithKeyPath:@"transform.rotation.x"];
        [basic setToValue:@(2*M_PI)];
        [basic setDuration:1.0f];
        [basic setRepeatCount:1];
        [_sublabel.layer addAnimation:basic forKey:@"rotationAnimation"];
        
        [self performSelector:@selector(afterTitle) withObject:nil afterDelay:0.5];
    }
}

- (void)afterTitle{
    _sublabel.text = _activityTitleArr[actIndex];
}

#pragma mark---轮播图delegate
- (void)scrollIndexWith:(NSInteger)index{
    CLog(@"index===%ld",(long)index);
    if (_imageArr.count == 0) {
        return;
    }
    NSDictionary *imgvoDic = _imgvoArr[index];
    NSString *url = imgvoDic[@"url"];
    NSString *isVoucher = imgvoDic[@"isVoucher"];
    
    if ([isVoucher isEqualToString:@"1"]){
        if([QUserInfo sharedInfo].loginModel){
            if   (url.length > 0){
                QActiveWebViewVC *vc = [[QActiveWebViewVC alloc] init];
                vc.title = imgvoDic[@"title"];
                vc.url = url;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                return;
            }
        }else{
            
            [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"您还未登录,请登录" leftTitle:@"取消" rightTitle:@"立即登录" type:1 myBlock:^(NSInteger tag) {
                if(tag == 1){
                    QLoginVC *vc = [[QLoginVC alloc] init];
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }];
        }
        
    }else{
        if(url.length > 0){
            QWebViewVC *vc = [[QWebViewVC alloc] init];
            vc.style = WebNetWorkStyle;
            vc.url = url;
            vc.title = imgvoDic[@"title"];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            return;
        }
    }
}


#pragma mark --用户是否登陆
- (void)notLogin{
    
    [QViewUtility showAlertChooseViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"您还未登录,请登录" leftTitle:@"取消" rightTitle:@"立即登录" type:1 myBlock:^(NSInteger tag) {
        if(tag == 1){
            QLoginVC *vc = [[QLoginVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }];
}

#pragma mark --- 定位
- (void)setLocationManager{
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    [self.locationManager startUpdatingLocation];
    _search = [[AMapSearchAPI alloc] init];
    _search.delegate = self;
}

#pragma mark --- 定位成功
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location{
    [self.locationManager stopUpdatingLocation];
    AMapPOIAroundSearchRequest *request = [[AMapPOIAroundSearchRequest alloc] init];
    request.location = [AMapGeoPoint locationWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
    request.offset = 1;
    request.requireExtension = YES;
    [QUserInfo sharedInfo].lat = [NSString stringWithFormat:@"%lf",location.coordinate.latitude];;
    [QUserInfo sharedInfo].lon = [NSString stringWithFormat:@"%lf",location.coordinate.longitude];;
    [_search AMapPOIAroundSearch:request];
}
#pragma mark --- 定位失败
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error{
    [self.locationManager stopUpdatingLocation];
}
#pragma mark --- 实现POI搜索结果
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if(response.pois.count == 0){
        return;
    }
    AMapPOI *p = response.pois[0];
    [QUserInfo sharedInfo].cityStr = p.city;
    [QUserInfo sharedInfo].districtStr = p.district;
    [QUserInfo sharedInfo].address = p.address;
    
    CLog(@"市===%@  区===%@ ==%@",[QUserInfo sharedInfo].cityStr,[QUserInfo sharedInfo].districtStr,p.address);
}

#pragma mark --获取轮播图数据
- (void)requestData{
    NSString *url = [QParamService urlWithAction:@"homepage"];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameters:nil completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [_imgvoArr removeAllObjects];
            [_imageArr removeAllObjects];
            _imgvoArr = basModel.items[@"imgvoList"];//***********************所有轮播数据
            for (NSDictionary *dic in _imgvoArr) {
                [_imageArr addObject:dic[@"imgUrl"]];
            }
            _headview.imageData = _imageArr;//***********************所有轮播图片地址
            _activityTitleArr = [NSMutableArray array];
            _activityImgArr = [NSMutableArray array];
            NSArray *activityArr = basModel.items[@"activityList"];//***********************所有活动数据
            if(activityArr.count){
                for(NSDictionary *dic in activityArr){
                    [_activityTitleArr addObject:dic[@"imgUrl"]];
                    NSString *u = dic[@"url"];
                    if(u.length > 0){
                        [_activityImgArr addObject:dic[@"url"]];
                    }
                }
                [_timer invalidate];
                _timer = nil;
                _timer =  [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(runTimeTitle) userInfo:nil repeats:YES];
                _sublabel.text = _activityTitleArr[0];
            }else{
                return;
            }
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

#pragma mark --- 用户个人中心
- (void)requestDataMySelf{
    NSString *url = [QParamService urlWithAction:@"myCentre"];
    NSDictionary *param = [QParamService getMyCentreData:@"2"];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            QLoginModel *loginModel = [QLoginModel objectFromDict:basModel.items];
            [QDataUtility updateLoginModel:loginModel];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            if([basModel.errMsg isEqualToString:@"请重新登录"]){
                [QDataUtility deleteLoginModel];
            }
        }
    }];
}

#pragma mark --- 是否有未读消息
- (void)requestUnlookMessage{
    NSString *UUID = [QParamService getUUID];
    NSString *url = [QParamService urlWithAction:@"getIsUnLook"];
    NSDictionary *param = [QParamService getIsUnLookWithMac:UUID];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSString * size = basModel.items[@"size"];
            if ([size isEqualToString:@"0"]) {
                [self.tabBarController.tabBar hideBadgeOnItemIndex:2];
            }else{
                [self.tabBarController.tabBar showBadgeOnItemIndex:2];
            }
            
        }else{
        }
    }];
    
}

#pragma mark --- 是否有订单未支付
- (void)requestNoPayOrderData{
    NSString *url = [QParamService urlWithAction:@"getOrderStateNum"];
    NSDictionary *param = [QParamService noPayOrder];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            QNoPayOrderModel * model = [QNoPayOrderModel objectFromDict:basModel.items];
            if ([model.num isEqualToString:@"0"]) {
                [QUserInfo sharedInfo].unPayOrder = NO;
                
            }else{
                [QUserInfo sharedInfo].unPayOrder = YES;
                [QUserInfo sharedInfo].unPayCount = [NSString stringWithFormat:@"%@",model.num];
            }
        }else{
        }
    }];
    
    [self requestUnlookMessage];
}

#pragma mark --- 切换模式与状态(活动)
- (void)requestActivityData{
    NSString *url = [QParamService urlWithAction:@"getInviterActivityInfo"];
    NSDictionary *param = [QParamService getInviterActivityInfo];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return;
        }
        NSLog(@"dic:%@",dict);
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
        }else{
        }
    }];
}


#pragma mark -- ScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    /*配对使用，开始拖动时候，不再允许响应*/
    NSLog(@"scrollView:%f",scrollView.contentOffset.x);
}


/**
 首页菜单配置
 积分商城 ：sort：”1”
 积分签到 ：sort：”2”
 设备管理 ：sort：”3”
 推荐有奖 ：sort：”4”
 邀请好友 ：sort：”5”
 */
#pragma mark ---获取后台动态配置
- (void)testRequestData{
    NSString *url = [QParamService urlWithAction:@"usercard/getMenuConfig"];
    NSDictionary *param = [QParamService getUsercard];
    
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSDictionary *tmpDic = [dict objectForKey:@"items"];
            
            NSLog(@"tmpDic:%@",tmpDic);
            
            //NSArray *array = [tmpDic objectForKey:@"list"];
            NSArray *array =  [QMainModel mj_objectArrayWithKeyValuesArray:[basModel.items objectForKey:@"list"]];
            [self.bottomArray removeAllObjects];
            if (array.count>0) {
                for (QMainModel *model in array) {
                    NSString *type = model.type;
                    NSString *isDisplay = model.isDisplay;
                    if ([type isEqualToString:@"1"]&&[isDisplay isEqualToString:@"0"]) {
                        [self.bottomArray addObject:model];
                    }
                }
            }
            float imgW = self.view.bounds.size.width /4;
            self.footView.contentSize = CGSizeMake(_bottomArray.count*imgW, self.footView.bounds.size.height);
            self.footView.delegate = self;
            for (int i = 0; i<self.bottomArray.count; i++) {
                QMainModel *model = [_bottomArray objectAtIndex:i];
                NSString *imgUrl = model.imgUrl;
                NSString *title = model.title;
                NSString *sort = model.sort;
                NSInteger sortNum = [sort integerValue];
                CustomView *view = [[CustomView alloc]initWithFrame:CGRectMake(i*imgW, 0, imgW, imgW)];
                [view.cButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
                view.cButton.tag = sortNum+100;
                [view.cImgView sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"Main_shop.png"]];
                view.cLabel.text = title;
                [self.footView addSubview:view];
                if (_bottomArray.count > 4) {
                    
                    _leftScroBtn.hidden = NO;
                    _rightScroBtn.hidden = NO;
                }
            }
            
        }else{
            
        }
    }];
    
}

#pragma --mark banner点击跳转
- (void)buttonAction:(UIButton *)sender{
    
    NSLog(@"sender:%ld",(long)sender.tag);
    int index = (int)sender.tag - 100;
    
    switch (index) {
            
        case 1://积分商城
        {
            if([QUserInfo sharedInfo].loginModel){
                QPointShopVC * vc = [[QPointShopVC alloc]init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self notLogin];
            }
        }
            break;
        case 2://积分签到
        {
            if([QUserInfo sharedInfo].loginModel){
                QPointsVC * vc = [[QPointsVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self notLogin];
            }
            
        }
            break;
        case 3://设备管理
        {
            if([QUserInfo sharedInfo].loginModel){
                QActivityWebVC *vc = [[QActivityWebVC alloc] init];
                vc.url = [NSString stringWithFormat:@"http://www.ydaol.com/oilWX_api/client/EquipmentList.html?token=%@",[QUserInfo sharedInfo].loginModel.token];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self notLogin];
            }
            
        }
            break;
            
        case 4://推荐有奖4
        {
            
            if([QUserInfo sharedInfo].loginModel){
                QTawardVC *vc = [[QTawardVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                vc.textString = @"1";
            }else{
                [self notLogin];
            }
        }
            break;
        case 5://邀请好友5
        {
            if([QUserInfo sharedInfo].loginModel){
                QTawardVC *vc = [[QTawardVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                vc.textString = @"2";
                
            }else{
                
                [self notLogin];
            }
        }
            break;
        case 6://机手带班联盟
        {
            if([QUserInfo sharedInfo].loginModel){
                DaiBanWebVC *vc = [[DaiBanWebVC alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
                QMainModel *model = [_bottomArray objectAtIndex:4];
                vc.url = model.htmlUrl;
                
            }else{
                
                [self notLogin];
            }
        }
            break;
            
        default:
            
            
            break;
    }
    
}


#pragma ----mark上传用户通讯录数据
- (void)checkArchive{
    
    //获取数组
    FileManager *fileManager = [[FileManager alloc]init];
    MessageObject * datas = [fileManager readMessageObject];
    NSArray *array =  datas.userInfo;
    if (array.count == 0) {
        return;
    }
    NSString *str = [array componentsJoinedByString:@";"];
    NSLog(@"str:%@",str);
    NSString *url = [QParamService urlWithAction:@"uab/save"];
    NSDictionary *param = [QParamService saveAddressBookWithInfo:str];
    [[QHttpManager sharedManager] POST:url parameterMD5jm:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setValue:[NSDate date] forKey:@"updateAddressBook"];
            
            CLog(@"===上传成功");
        }else{
            CLog(@"===上传失败");
        }
    }];
    
}

- (NSString *)calculateWeek:(NSDate *)date{
    //计算week数
    NSCalendar * myCalendar = [NSCalendar currentCalendar];
    myCalendar.timeZone = [NSTimeZone systemTimeZone];
    NSInteger week = [[myCalendar components:NSCalendarUnitWeekday fromDate:date] weekday];
    
    NSLog(@"week : %zd",week);
    switch (week) {
        case 1:
        {
            return @"周日";
        }
        case 2:
        {
            return @"周一";
        }
        case 3:
        {
            return @"周二";
        }
        case 4:
        {
            return @"周三";
        }
        case 5:
        {
            return @"周四";
        }
        case 6:
        {
            return @"周五";
        }
        case 7:
        {
            return @"周六";
        }
    }
    
    return @"";
}


- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
